// 角色页面实现
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible = true"
        >添加角色</el-button
      >

      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限列表 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限列表 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 == 0 ? '' : 'bdTop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限渲染 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限渲染 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showRolseEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog
      title="提示"
      @close="addRolesDialogClosed"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色信息 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editRolesdialogVisible"
      width="50%"
      @close="editRolesDialogClose"
    >
      <!--表单区域  -->
      <el-form
        ref="addRolesFormRef"
        :model="editRolesForm"
        :rules="addFormrules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRIghtdialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件权限列表 -->
      <el-tree
        show-checkbox
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRIghtdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      rolesList: [],
      addDialogVisible: false,
      //分配角色权限对话框
      setRIghtdialogVisible: false,
      //所有权限的列表
      rightsList: [],
      //树形权限控件
      treeProps: {
        label: "authName",
        children: "children",
      },
      //角色id
      roleID: "",
      //默认选中节点的ID数组
      defkeys: [],
      //添加用户信息
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      //校验规则
      addFormrules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入用户描述", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      editRolesdialogVisible: false,
      //修改角色信息内容
      editRolesForm: {},
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("请求角色列表失败");
      }
      // this.$message.success("请求角色列表成功");
      this.rolesList = res.data;
      console.log(this.rolesList);
    },
    //添加角色
    addRoles() {
      //校验表单信息
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //添加成功校验的数据
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getRolesList();
      });
    },
    //关闭对话框后清空内容
    addRolesDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //编辑角色信息
    async showRolseEditDialog(id) {
      console.log(id);
      //获取当前角色的ID
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败");
      }
      //this.$message.success("请求成功");
      console.log(res);
      this.editRolesForm = res.data;
      this.editRolesdialogVisible = true;
    },
    //关闭用户信息修改页面重置信息
    editRolesDialogClose() {
      this.$refs.addRolesFormRef.resetFields();
    },
    //点击提交按钮时校验并提交更改信息
    editRolesInfo() {
      //校验信息
      this.$refs.addRolesFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        //发送put请求，更改新输入的信息
        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesForm.roleId,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新角色信息失败");
        }
        this.editRolesdialogVisible = false;
        //刷新数据列表
        this.getRolesList;
        this.$message.success("更新角色信息成功");
      });
    },
    //删除角色
    async removeRolesById(id) {
      const confirmResoule = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //确认删除， 返回的字符串为confirm
      //如果没有确认删除， 返回cancel
      console.log(confirmResoule);
      if (confirmResoule !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.err("删除失败");
      }
      this.$message.success("删除成功");
      //更新用户列表
      this.getRolesList();
    },
    //弹窗提示用户是否删除权限
    async removeRightById(role, rightId) {
      const confirmResoult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResoult !== "confirm") {
        return this.$message.info("取消了删除");
      }
      this.$message.success("成功删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.err("删除权限失败");
      }
      //重新给子权限赋值
      role.children = res.data;
      // this.$message.success("删除权限成功");
      //this.getRolesList();
    },
    //分配权限
    async showSetRightDialog(role) {
      this.roleID = role.id;
      //获取所有权限
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.err("请求权限列表失败");
      }
      //获取权限的数据保存在rightsList中
      this.rightsList = res.data;
      console.log(this.rightsList);
      //调用递归函数或得当前角色三级节点操作，保存在defkeys数组中
      this.getLeafKey(role, this.defkeys);

      this.setRIghtdialogVisible = true;
    },
    //通过递归的形式获取角色下所有三级权限的ID，并保存再defkeys中
    getLeafKey(node, arr) {
      //如果当前node的节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      //递归遍历所有节点
      node.children.forEach((item) => this.getLeafKey(item, arr));
    },
    //监听分配权限对话框关闭时事件，清空数组
    setRightDialogClosed() {
      this.defkeys = [];
    },
    //分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);
      //将或得的ID以逗号隔开
      const idStr = keys.join(",");
      //发起请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.err("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRIghtdialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
// .el-col {
//   margin-left: 40px;
// }
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>